package org.jeecg.common.modules.apiPermission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.modules.apiPermission.entity.ApiPermission;
import org.jeecg.common.modules.apiPermission.mapper.ApiPermissionMapper;
import org.jeecg.common.modules.apiPermission.service.IApiPermissionService;
import org.jeecg.common.util.enums.BusinessTypeEnum;
import org.jeecg.common.util.enums.DelFlagEnum;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author guoyh
 * @ClassName ApiPermissionServiceImpl
 * @Description
 * @since 2020/8/11 00:06
 **/
@Service
@Slf4j
public class ApiPermissionServiceImpl extends ServiceImpl<ApiPermissionMapper, ApiPermission> implements IApiPermissionService {

    @Override
    public boolean hasPermission(String username, BusinessTypeEnum businessTypeEnum, String url) {
        Set<String> permissions = queryByBusinessEnum(businessTypeEnum);
        return permissions.stream().anyMatch(item -> hasPermission(url, item));
    }

    @Override
    public Set<String> queryByBusinessEnum(BusinessTypeEnum businessTypeEnum) {
        LambdaQueryWrapper<ApiPermission> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ApiPermission::getBusinessId, businessTypeEnum.getId());
        queryWrapper.eq(ApiPermission::getDelFlag, DelFlagEnum.NORMAL.getCode());
        return list().stream().map(ApiPermission::getUrl).collect(Collectors.toSet());
    }

    private boolean hasPermission(String url, String permission) {
        return Pattern.matches(permission, url);
    }
}
